package com.elite.groovy.callback

import cn.com.elite.PropertiesUtil
import cn.com.kh.HttpClientProxy
import com.elite.groovy.util.EliteBean
import com.elite.groovy.util.Util
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.security.MessageDigest
import java.text.SimpleDateFormat

public class autoGetQNXLEvent implements ServiceBackInvoke {
	private static final Log log=LogFactory.getLog(autoGetQNXLEvent.class);
	public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

		//查询拼接sessionID
		def  querySql1=" select Sessionid from (Select R1.Sessionid From Qnxl_Call_Detail R1 Left Join Qnxl_Event R2 On R1.Rec_Guid = R2.Rec_Guid Where 1 = 1 and R2.Event_Guid Is Null And R1.Calltime > Sysdate - 1 And (R1.Sessionid Is Not Null or R1.Sessionid != '')) t where ROWNUM <= 1000";
				
		def resultlist=eliteBean.chaxun_sql(querySql1, "dataSource");
		
		log.debug("条数："+resultlist.size);

		if(resultlist.size>=0){
		
		StringBuffer sb = new StringBuffer();
		for(int i=0;i<resultlist.size;i++){
			sb.append(String.valueOf(resultlist.get(i).get("Sessionid"))+',');
		}
		StringBuffer req_Sessionid=sb.replace(sb.length() - 1, sb.length(), "");
		
		
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		
		PropertiesUtil cfg = new PropertiesUtil();	
		String Te_Entid = cfg.readValue("QingNiuXL.EntId");
		String Te_Entsecret = cfg.readValue("QingNiuXL.SECRET_KEY");
		String Te_Timestamp = Util.getNowString("yyyyMMddHHmmss");
		//String Te_Timestamp = df.format(new Date());
		String Te_Requestid = "SYSTEM";
		String Te_Mac = Util.getMD5Str(Te_Entid + Te_Entsecret + Te_Timestamp + Te_Requestid).toUpperCase();

		String proxyIp = cfg.readValue("QingNiu.ProxyIP");
		int proxyPort = cfg.readValue("QingNiu.ProxyPort").toInteger();
		
		//调用青牛续联详单获取接口地址
		def httpURL=cfg.readValue("QingNiuXL.CCODURL")+"/agent/dps/query";

		//拼接发送内容
		def sendBody = "{\"entID\":\""+Te_Entid+"\",\n" +
				"    \"requestID\":\""+Te_Requestid+"\",\n" +
				"    \"timestamp\":\""+Te_Timestamp+"\",\n" +
				"    \"mac\":\""+Te_Mac+"\",\n" +
				"    \"sessionIds\":\""+req_Sessionid+"\"}";

		//log.debug("系统拼接后的发送报文Body:" + sendBody);
		
		String reJson = HttpClientProxy.sendPost(httpURL, sendBody, proxyIp,proxyPort);
		
		
		try {
			//解析返回Json内容
			JSONObject jsonObject = new JSONObject(reJson);

			//解析所需要的值
			String reCode = GetJV(jsonObject, "code");
			String reMsg = GetJV(jsonObject, "msg");
			if(reCode!=-1){
			String reData = GetJV(jsonObject, "data");
			JSONArray jsonArray = new JSONArray(reData);
			int dataArrayLen = jsonArray.length();

			//log.debug("返回Code：" + reCode + "返回Msg：" + reMsg + "返回DataArray：" + jsonArray.toString() + "DataArray Size:" + dataArrayLen);

			//处理主数据
			JSONObject dataObject = null;
			for(int i = 0; i < dataArrayLen; i++) {
				dataObject = jsonArray.getJSONObject(i);
				def agentId = GetJV(dataObject, "agentId");
				def alertDuration = GetJV(dataObject, "alertDuration");
				def ani = GetJV(dataObject, "ani");
				def callResult = GetJV(dataObject, "callResult");
				def dani = GetJV(dataObject, "dani");
				def ddnis = GetJV(dataObject, "ddnis");
				def dnis = GetJV(dataObject, "dnis");
				def endTime = GetJV(dataObject, "endTime");
				def endType = GetJV(dataObject, "endType");
				def entID = GetJV(dataObject, "entID");
				def sessionId = GetJV(dataObject, "sessionId");
				def startTime = GetJV(dataObject, "startTime");
				def talkDuration = GetJV(dataObject, "talkDuration");
				def userData = GetJV(dataObject, "userData");
				
				if(endType=='-1'){endType=0;}
				
	//获取本次补全参数、客户、处理人、处理组、工号、分机号数据
	def querySql2="SELECT Rec_Guid,CUSTOMER_GUID,staff_id,rolegroup_id,extension FROM QNXL_CALL_DETAIL  WHERE SESSIONID='" + sessionId + "'";
	def queryList1=eliteBean.chaxun_sql(querySql2, "dataSource");
	def queryMap1=queryList1[0];
	def Rec_Guid = queryMap1.get("Rec_Guid");
	def customerguid =queryMap1.get("CUSTOMER_GUID");
	def staff_id =queryMap1.get("staff_id");
	def rolegroup_id =queryMap1.get("rolegroup_id");
	def extension =queryMap1.get("extension");
	
	
	

	//添加QNXL_EVENT数据
	def insertSQL="insert into QNXL_EVENT (EVENT_GUID, REC_GUID, AGENTID, ALERTDURATION, ANI, CALLRESULT, DANI, DDNIS, DNIS,    ENDTIME, ENDTYPE, ENTID, SESSIONID, STARTTIME, TALKDURATION, USERDATA, SYNC_TIME) values ('"+Rec_Guid+"', '" + Rec_Guid + "', '" + agentId + "', '" + alertDuration + "', '" + ani + "', '" + callResult + "', '" + dani + "', '" + ddnis + "', '" + dnis + "', '" + endTime + "', '" + endType + "', '" + entID + "', '" + sessionId + "', '" + startTime + "', '" + talkDuration + "', '" + userData + "', Sysdate)";
				//log.debug("调用话单详情接口处理成功SQL:"+insertSQL);
				eliteBean.update(insertSQL,'dataSource');
				
	//添加EVENT数据
	def insertSQL2="insert into EVENT (EVENT_GUID, CALLTYPE, CUSTOMER_GUID, DNIS, ANI, CALLSTARTTIME, CALLENDTIME,HANGUPTYPE,HANDLEBY_ID, HANDLEGROUP_ID, CALLESTABLISHED, RECORD_GUID, EXTENSION,AGENTID, CALLRESULT,WORKSTARTTIME, WORKENDTIME) values ('"+Rec_Guid+"', '2','"+customerguid+"', '" + dnis + "', '" + ani + "', '" + startTime + "', '"+ endTime + "','" + endType + "', '" + staff_id + "', '" + rolegroup_id + "', '" + callResult + "', '" + Rec_Guid + "', '" + extension + "','" + agentId + "', '" + callResult + "', '" + startTime + "','" + endTime + "' )";
				
			   // log.debug("电话详情加入EVENT表SQL:"+insertSQL2);
				eliteBean.update(insertSQL2,'dataSource');
				
	        log.debug("调用话单详情接口处理成功sessionId:"+sessionId);			
				
			}
		   }
		} catch (JSONException e) {
			log.error("电销系统处理异常！可能是返回Json格式不合法",e);
		} catch (Exception e) {
			log.error("电销系统处理异常！可能是处理逻辑出现异常导致",e);
		}
		
	  }else{
		   log.debug("未查询到待获取记录");
		}
	}

	private static String MD5(String s) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] bytes = md.digest(s.getBytes("utf-8"));
			return toHex(bytes);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private static String toHex(byte[] bytes) {

		final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
		StringBuilder ret = new StringBuilder(bytes.length * 2);
		for (int i = 0; i < bytes.length; i++) {
			ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);
			ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
		}
		return ret.toString();
	}

	public static String GetJV(JSONObject inJson, String getKey) {
		String Rev_Value = null;
		try {
			Rev_Value = inJson.getString(getKey);
			log.debug("GetJV 获取参数值(String)-" + getKey + ":" + Rev_Value);
		} catch (Exception e) {
			try {
				Rev_Value = String.valueOf(inJson.getInt(getKey));
				log.debug("GetJV 获取参数值(Integer)-" + getKey + ":" + Rev_Value);
			} catch (Exception e1) {
				Rev_Value = "";
				log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
				Rev_Value = "";
			}
		}
		return Rev_Value;
	}
}